#!/usr/bin/python3

import serial
from tracer import Tracer, TracerSerial, QueryCommand
from PIL import Image, ImageDraw, ImageFont

from gpiozero import PWMLED

import lcd_driver

import threading
import time

BL_GPIO = 12            # BCM 12

ser = serial.Serial('/dev/ttyS0', 9600, timeout = 1)
tracer = Tracer(0x16)
t_ser = TracerSerial(tracer, ser)
query = QueryCommand()
t_ser.send_command(query)

# LCD init
lcd_driver.Open()

bl = PWMLED(BL_GPIO, active_high=False, initial_value=0, frequency=1000)
bl.value = 1

# Image
image = Image.new('1', (256, 128))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype('fonts/New X Digital Light tfb.ttf', 50)


def GetData():
	try:
		t_ser.send_command(query)
		time.sleep(0.1)
		result = t_ser.receive_result()

		draw.rectangle([(0, 0), (255, 127)], fill=0)
		draw.text((0, 0), '{:.2f}'.format(result.charge_current), fill=1, font=font)

		lcd_driver.Display(image.tobytes())

		print("ok")
	except Exception as e:
		print(e)
		pass
	return

while 1:
	time.sleep(2)
	GetData()







